import _config from '@/config.js'
import * as fyStorage from '@/utils/storageUtils.js'
import { toFirst, timespantoYMDhms } from '@/common/tools.js'
export default {
	namespaced: true,
	state: {
		LoginId: 0,
		IsOpen: false,
		SocketTask: false,
		IsOnline: false,
		ToUser: {
			user_id: 0,
			username: '',
			userpic: ''
		},
		userInfo: {},
		chatList: [],
		ChatDetail: [],
		hart: null,
		conn_hart:null

	},
	getters: {
		allNotRead: state => {
			let notread = 0
			state.chatList.forEach(arr => {
				notread += arr.noread
			})
			return notread
		}
	},
	mutations: {
		setChatList(state, chatList) {
			state.chatList = chatList
		},
		// 创建聊天对象
		createToUser(state, ToUser) {
			state.ToUser = ToUser
			state.ChatDetail = fyStorage.getChatLog(state.userInfo.id, state.ToUser.user_id)
		},
		reloadDetail(state) {
			state.ChatDetail = fyStorage.getChatLog(state.userInfo.id, state.ToUser.user_id)
		},
		// 关闭聊天对象
		closeToUser(state) {
			state.ToUser = {
				user_id: 0,
				username: '',
				userpic: ''
			}
		},
		// 存储与某个用户聊天内容列表
		saveChatDetail(state, { list, toId }) {
			// chatdetail_[当前用户id]_[聊天对象id]
			let myId = state.userInfo.id
			toId = toId ? toId : state.ToUser.user_id
			fyStorage.setChatLog(myId, toId, list)
		},
		saveChatList(state, chatlist) {
			state.chatList = chatlist
			fyStorage.setChatList(state.userInfo.id, chatlist)
		},
		setUserInfo(state, userinfo) {
			state.userInfo = userinfo
		}
	},
	actions: {
		openSocket({ state, dispatch, commit }) {
			var token = fyStorage.getToken()
			if (!token) return

			if (state.IsOpen) return
			state.SocketTask = uni.connectSocket({
				url: _config.ws_url,
				header: { 'selftoken': token },
				complete: () => {

				}
			})
			state.SocketTask.onOpen(() => {
					// 将连接状态设为已连接
					console.log('将连接状态设为已连接')
					clearInterval(state.conn_hart)
					state.IsOpen = true
					state.SocketTask.send({
						data: JSON.stringify({ msg: 'pong', type: 1 })
					})
					state.hart = setInterval(() => {
						state.SocketTask.send({
							data: JSON.stringify({ msg: 'pong', type: 1 })
						})
					}, 5 * 60 * 1000)
					dispatch('initchat')
				}),
				state.SocketTask.onClose(() => {
					console.log('连接已关闭')
					state.IsOpen = false
					state.SocketTask = false
					state.IsOnline = false
					// 清空会话列表
					// 更新未读数提示
					//关闭心跳
					clearInterval(state.hart)
					state.hart = null
					if(!state.conn_hart){
						state.conn_hart=setInterval(()=>{
							dispatch("openSocket")
						},5*1000)
					}
					
					
				})
			// 监听错误
			state.SocketTask.onError(err => {
				console.log('连接错误', err)
				state.IsOpen = false
				state.SocketTask = false
				state.IsOnline = false
			})
			// 监听接收信息
			state.SocketTask.onMessage(e => {
				console.log('接收消息', e)
				// 字符串转json
				let res = JSON.parse(e.data)
				switch (res.type) {
					case 1:
						break
					case 2:
						break
					default:
						dispatch('handleChatMessage', res)
						break
				}
			})
		},
		initchat({ state, commit, dispatch }) {
			var userinfo = fyStorage.getUserInfo()
			commit('setUserInfo', userinfo)
			var chatList = fyStorage.getChatList(state.userInfo.id)
			commit('setChatList', chatList)
			dispatch('updateTabbarBadge')
		},
		//处理接收消息
		handleChatMessage({ state, dispatch }, data) {
			// 全局通知接口
			uni.$emit('UserChat', data);
			// 存储到chatdetail
			dispatch('updateChatDetailToUser', {
				data,
				send: false
			})
			// 更新会话列表
			dispatch('updateChatList', {
				data,
				send: false
			})
		},
		/*
		 *创建聊天 如有惟独 清空未读数据
		 */
		async createToUser({ state, dispatch, commit }, toUserInfo) {
			commit('createToUser', toUserInfo)
			const { user_id, username, userpic } = toUserInfo
			let i = state.chatList.findIndex(v => {
				return v.user_id == user_id
			}) 
			if (i != -1) {
				state.chatList[i].noread = 0
				commit('saveChatList', state.chatList)
				// 更新未读数 
				await dispatch('updateTabbarBadge')
			}

		},

		// 更新聊天会话列表
		async updateChatList({ state, dispatch, commit }, { data, send }) {
			console.log('更新聊天会话列表', data);
			// 是否是本人发送
			let isMySend = send
			console.log(isMySend ? '本人发送的信息' : '不是本人发送的');
			// 获取之前会话
			let chatList = fyStorage.getChatList(state.userInfo.id)
			// 判断是否已存在该会话，存在：将当前会话置顶；不存在：创建并追加至头部
			let i = chatList.findIndex((v) => {
				return v.user_id == data.toId || v.user_id == data.fromId;
			})
			// 不存在,创建会话
			if (i === -1) {
				// 接收到的消息转会话
				let obj = await dispatch('formatChatListObject', {
					data,
					send
				})
				// 忽略本人发送
				if (!isMySend) {
					obj.noread = 1;
				}
				console.log('不存在当前会话,创建', obj);
				// 追加头部
				chatList.unshift(obj);
			} else {
				// 存在：将当前会话置顶,修改当前会话的data和time显示
				let item = chatList[i]
				item.data = data.msg
				item.type = data.type
				item.time = data.time
				// 当前聊天对象不是该id，未读数+1（排除本人发送消息）
				if (!isMySend && state.ToUser.user_id !== item.fromId) {
					item.noread++
				} else {
					item.noread = 0
				}
				console.log('存在当前会话', item);
				// 置顶当前会话
				chatList = toFirst(chatList, i)
			}
			// 存储到本地存储
			state.chatList = chatList
			commit('saveChatList', chatList)
			// 更新未读数 
			await dispatch('updateTabbarBadge')

		},
		updateTabbarBadge({ getters }) {
			var noreadcount = getters.allNotRead
			let pages = getCurrentPages();
			if (pages.length < 1) {
				return
			}
			let route = pages[pages.length - 1].route
			let routes = [
				"pages/index/index",
				"pages/group/index",
				"pages/pyq/index",
				"pages/message/index",
				"pages/mine/mine"
			]
			if (routes.indexOf(route) == -1) {
				return
			}

			if (noreadcount) {
				uni.setTabBarBadge({
					index: 3,
					text: `${noreadcount}`
				})
			} else {
				uni.removeTabBarBadge({
					index: 3
				})
			}


		},
		//登录用户发送信息
		async sendChatMessage({ state, dispatch }, data) {
			let _data = await dispatch('formatSendData', data)

			return new Promise((resolve, reject) => {
				state.SocketTask.send({
					data: JSON.stringify(_data),
					success(res) {
						// 更新与某个用户的消息历史记录
						dispatch('updateChatDetailToUser', {
							data: _data,
							send: true
						})
						dispatch('updateChatList', { data: _data, send: true })
						resolve(res)
					},
					fail(res) {
						console.log(res)
						reject(res)
					}
				})
			})


		},
		// 更新与某个用户聊天内容列表
		async updateChatDetailToUser({ state, dispatch, commit }, e) {

			let data = e.data
			let toId = e.send ? state.ToUser.user_id : data.fromId
			// 获取与某个用户聊天内容的历史记录
			let list = await dispatch('getChatDetailToUser', toId)
			list.push(e)

			// 存储到本地存储
			commit('saveChatDetail', {
				list,
				toId
			})
			//如果在当前窗口重载
			if (toId == state.ToUser.user_id) {
				commit('reloadDetail')
			}
		},
		async getChatDetailToUser({ state }, toId = 0) {
			let myId = state.userInfo.id
			toId = toId ? toId : state.ToUser.user_id
			return fyStorage.getChatLog(myId, toId)
		},
		//统一格式组装会话对象
		formatChatListObject({ state }, { data, send }) {
			return {
				user_id: send ? state.ToUser.user_id : data.fromId,
				avatar: send ? state.ToUser.userpic : data.fromImgsrc,
				username: send ? state.ToUser.username : data.fromName,
				update_time: timespantoYMDhms(data.time), // 最新消息时间戳
				data: data.msg,
				noread: 0 // 未读数
			}

		},
		// 组织发送格式
		formatSendData({ state }, data) {
			var t = new Date().getTime()
			return {
				toId: state.ToUser.user_id,
				fromId: state.userInfo.id,
				fromName: state.userInfo.name,
				fromImgsrc: state.userInfo.imgsrc,
				type: data.type,
				msg: data.msg,
				time: t
			}
		},
		closeSocket({ state }) {
			if (state.IsOpen) {
				state.SocketTask.close()
			}
		}

	}
}